<?php

namespace App\Kuafu\User\Controller\B;

use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\User\Enum\CodeEnum;
use App\Kuafu\User\Enum\RoleCodeEnum;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Model\UserRoleMapping;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Service\UserRoleService;
use App\Kuafu\User\Service\UserService;
use App\Kuafu\User\Validate\UserValidate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;


class UserController extends BaseController
{

    /**
     * 添加员工账号
     * @param Request $request
     * @return JsonResponse
     * @throws \Exception
     */
    public function addUser(Request $request)
    {
        //数据校验
        $valid = UserValidate::addUser($request);
        if ($valid) {
            return $this->fail(BaseCodeEnum::ERR_PARAM_PATH_ERROR, $valid);
        }

        UserService::addUser($request);
        return $this->success();
    }

    /**
     * 设置用户基本信息
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public function setUserInfo(Request $request)
    {
        $valid = UserValidate::setUserInfo($request);
        if ($valid) {
            return $this->fail(BaseCodeEnum::ERR_PARAM_PATH_ERROR, $valid);
        }
        UserService::setUserInfo($request->userId, $request->username, $request->mobile, $request->roles,
            $request->header('brandId'));
        return $this->success();
    }

    /**
     * 软删除用户
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public function deletedUser(Request $request)
    {
        // 不支持删除用户
        return $this->fail(BaseCodeEnum::ERR_PARAM_PATH_ERROR, '系统暂不支持删除用户');
        $valid = UserValidate::checkUserIsExist($request);
        if ($valid) {
            return $this->fail(BaseCodeEnum::ERR_PARAM_PATH_ERROR, $valid);
        }
        $i = UserService::deletedUser($request->userId);
        if (!$i) {
            return $this->fail(BaseCodeEnum::ERR_SERVER_ERROR, "删除失败");
        }
        return $this->success();
    }

    /**
     * 设置用户状态
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public function setUserStatus(Request $request)
    {
        $valid = UserValidate::setUserStatus($request);
        if ($valid) {
            return $this->fail(BaseCodeEnum::ERR_PARAM_PATH_ERROR, $valid);
        }

        $i = UserService::setUserStatus($request->userId, $request->status);
        if (!$i) {
            return $this->fail(BaseCodeEnum::ERR_SERVER_ERROR, "修改失败");
        }
        return $this->success();
    }

    /**
     * 获取用户列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getUserList(Request $request)
    {
        $name     = (string)$request->get('username', '');
        $mobile   = (string)$request->get('mobile', '');
        $roleId   = (int)$request->get('roleId', 0);
        $shopId   = (int)$request->get('shopId', 0);
        $status   = $request->get('status');
        $pageSize = (int)$request->get('pageSize', 20);
        $pageNum  = (int)$request->get('pageNum', 1);
        $brandId  = (int)$request->header('brandId') ?? 1;
        return $this->success(UserService::getUserList($name, $status, $pageSize, $pageNum, $brandId, $mobile, $roleId,
            $shopId, $request->url()));
    }

    /**
     * 查询用户信息
     * @return JsonResponse
     */
    public function getUserInfo(Request $request)
    {
        $brandId = $request->header('brandId');
        $valid   = UserValidate::checkUserIsExist($request);
        if ($valid) {
            return $this->fail(BaseCodeEnum::ERR_PARAM_PATH_ERROR, $valid);
        }
        $userInfo = UserService::getUserInfoById($request->userId, ['id', 'username', 'mobile', 'createdAt', 'status']);

        $roleList = UserRoleMapping::getRoleListByUserIds([$userInfo->id], $brandId);

        $brandList    = [];
        $shopList     = [];
        $merchantList = [];

        // 筛选 web 品牌 和 pos 门店
        foreach ($roleList as $roles) {
            if (empty($roles['role_many_rel']['type'])) {
                continue;
            }
            switch ($roles['role_many_rel']['type']) {
                case RoleCodeEnum::ROLE_WEB_TYPE:
                    $brandList[] = $roles['roleId'];
                    break;
                case RoleCodeEnum::ROLE_POS_TYPE:
                    $shopList[$roles['shopId']][] = $roles['roleId'];
                    break;
                case RoleCodeEnum::ROLE_BUSINESS_TYPE :
                    $merchantList[$roles['shopId']][] = $roles['roleId'];
                    break;
                default:
            }
        }

        $returnData = null;
        if ($userInfo) {
            $returnData = [
                'id'        => $userInfo['id'],
                'username'  => $userInfo['username'],
                'mobile'    => $userInfo['mobile'],
                'status'    => $userInfo['status'],
                'createdAt' => date("Y-m-d H:i:s", $userInfo['createdAt']),
                'userRole'  => [
                    'brandList'    => $brandList,
                    'shopList'     => $shopList ?: (object)[],
                    'merchantList' => $merchantList ?: (object)[]
                ],
            ];
        }
        return $this->success($returnData);
    }

    /**
     * 查询用户信息
     * @return JsonResponse
     */
    public function getCurrentUserInfo(Request $request)
    {
        $userInfo = UserService::getUserInfoById(AuthService::getUserId(),
            ['id', 'username', 'mobile', 'createdAt', 'status']);
        //获取用户角色名
        $roleList = UserRoleMapping::getRoleListByUserIds([$userInfo->id], $this->brandId);

        $roleName = '';
        collect($roleList)->each(function ($value) use (&$roleName) {
            if ($value['roleName'] && $value['type'] == RoleCodeEnum::ROLE_WEB_TYPE) {
                $roleName = $value['roleName'];
                return false;
            }
            return true;
        });

        $returnData = null;
        if ($userInfo) {
            $returnData = [
                'id'        => $userInfo['id'],
                'username'  => $userInfo['username'],
                'mobile'    => $userInfo['mobile'],
                'status'    => $userInfo['status'],
                'createdAt' => date("Y-m-d H:i:s", $userInfo['createdAt']),
                'userRole'  => $roleName,
            ];
        }
        return $this->success($returnData);
    }

    /**
     * 修改用户密码
     * @param Request $request
     * @return JsonResponse
     */
    public function setUserPassword(Request $request)
    {
        $valid = UserValidate::setUserPassword($request);
        if ($valid) {
            return $this->fail(UserCodeEnum::ERR_PARAM_PATH_ERROR, $valid);
        }
        UserService::setUserPassword($request->userId, $request->password);
        return $this->success();
    }

    /**
     * 修改用户手机号码
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public function setUserMobile(Request $request)
    {
        $userId = AuthService::getUserId();
        UserService::setUserMobile($request->mobile, $userId);
        return $this->success();
    }

}
